<?php

class SiteController extends Controller
{
	/**
	 * Declares class-based actions.
	 */
	public function actions()
	{
		return array(
			// captcha action renders the CAPTCHA image displayed on the contact page
			'captcha'=>array(
				'class'=>'CCaptchaAction',
				'backColor'=>0xFFFFFF,
			),
			// page action renders "static" pages stored under 'protected/views/site/pages'
			// They can be accessed via: index.php?r=site/page&view=FileName
			'page'=>array(
				'class'=>'CViewAction',
			),
		);
	}

	/**
	 * This is the default 'index' action that is invoked
	 * when an action is not explicitly requested by users.
	 */
	public function actionIndex()
	{
		$toView = array();
		$oGoods = new Goods();
        $oPhotos = new Photos();
        $oGallery = new Gallery();
        $oGoodsView = new GoodsView();

		$topIds = $oGoodsView->getTopGoodsId();
		if($topIds)
		{
			$toView['oTop'] = $oGoods->id($topIds)->limit(20)->findAll();
			$oPhotos->selectMainByRowset($toView['oTop']);
		}

        $toView['oGallery'] = $oGallery->findByAttributes(array('is_main' => 1));
        $oPhotos->selectByRow($toView['oGallery']);

		$oCategories = new Categories();
		$toView['oCategories'] = $oCategories->getAll(19, true, true, 'goods');
		$oPhotos->selectMainByRowset($toView['oCategories']);

		$title = 'Интернет магазин '. Yii::app()->name .'. Оригинальная обувь, одежда и сумки из америки.';
		$description = 'Выбирайте оригинальную обувь, одежду, сумки, аксессуары америкиканских брендов. Бесплатная доставка. Возврат 365 дней.';
		$this->addTitle($title)
			 ->addKeywords('Обувь, одежда, сумки, аксессуары, америка, usa')
			 ->addDescription($description);

        $this->layout='//layouts/main';
        $this->render('index', $toView);
	}

	/**
	 * This is the action to handle external exceptions.
	 */
	public function actionError()
	{
		if($error=Yii::app()->errorHandler->error)
		{
			if(Yii::app()->request->isAjaxRequest)
				echo $error['message'];
			else
				$this->render('error', $error);
		}
	}

	/**
	 * Displays the contact page
	 */
	public function actionContact()
	{
		$model=new ContactForm;
		if(isset($_POST['ContactForm']))
		{
			$model->attributes=$_POST['ContactForm'];
			if($model->validate())
			{
				$name='=?UTF-8?B?'.base64_encode($model->name).'?=';
				$subject='=?UTF-8?B?'.base64_encode($model->subject).'?=';
				$headers="From: $name <{$model->email}>\r\n".
					"Reply-To: {$model->email}\r\n".
					"MIME-Version: 1.0\r\n".
					"Content-Type: text/plain; charset=UTF-8";

				mail(Yii::app()->params['adminEmail'],$subject,$model->body,$headers);
				Yii::app()->user->setFlash('contact','Thank you for contacting us. We will respond to you as soon as possible.');
				$this->refresh();
			}
		}
		$this->render('contact',array('model'=>$model));
	}

	/**
	 * Displays the login page
	 */
	public function actionLogin()
	{
		$model=new LoginForm;

		// if it is ajax validation request
		if(isset($_POST['ajax']) && $_POST['ajax']==='login-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}

		// collect user input data
		if($this->_isPost())
		{
			$model->attributes=$this->_getPost();
			// validate user input and redirect to the previous page if valid
			if($model->validate() && $model->login())
				$this->redirect(Yii::app()->user->returnUrl);
		}
		// display the login form
		$this->render('login',array('model'=>$model));
	}

	/**
	 * Logs out the current user and redirect to homepage.
	 */
	public function actionLogout()
	{
		Yii::app()->user->logout();
		$this->redirect(Yii::app()->homeUrl);
	}

	public function actionSubscribe()
	{
		if(!$this->_isPost())
			exit;

		$oSubscribe = new Subscribe();

		$data = $this->_getPost();

		if(empty($data) || (empty($data['email']) && empty($data['phone'])))
		{
			echo json_encode(array('success' => false));
			exit;
		}

		$oString = new String();

		if(!empty($data['phone']))
			$data['phone'] = preg_replace('`\D+`i', '', trim($oString->stripTagsAttributes($data['phone'])));

		if(!empty($data['email']))
			$data['email'] = trim($oString->stripTagsAttributes($data['email']));

		$data['date'] = date('Y-m-d H:i:s');
		$data['ip'] = !empty($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : '';
		$data['url'] = !empty($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '';
		$data['browser'] = !empty($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : '';

		$oSubscribe->setAttributes($data);
		$oSubscribe->save(true);

		echo json_encode(array('success' => true, 'text' => '<div class="text">Ты всегда бедуш знать о новых поступлениях</div>')); exit;
	}

}